package com.ikkong.sn.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.ikkong.core.base.BaseController;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.jfinal.ext.kit.JsonKit;
import com.ikkong.core.jfinal.ext.shiro.ClearShiro;
import com.ikkong.core.jfinal.ext.shiro.ShiroKit;
import com.ikkong.core.toolbox.Record;
import com.ikkong.core.toolbox.kit.DateKit;
import com.ikkong.sn.model.SnOrderIn;
import com.ikkong.sn.model.SnOrderInlog;
import com.ikkong.system.controller.base.UrlPermissController;
import com.ikkong.sn.model.SnStore;
import com.ikkong.sn.service.SnStoreService;
import com.ikkong.sn.service.impl.SnStoreServiceImpl;
import com.ikkong.system.util.CommonUtil;
import org.apache.poi.ss.usermodel.DateUtil;
import org.beetl.sql.core.kit.StringKit;

/**
 * Generated by Blade.
 * 2019-04-30 09:50:06
 */
public class SnStoreController extends UrlPermissController {
	private static String CODE = "snStore";
	private static String PERFIX = "sn_store";
	private static String LIST_SOURCE = "SnStore.list";
	private static String BASE_PATH = "/platform/snStore/";
	
	SnStoreService service = new SnStoreServiceImpl();
	
	public void index() {
		setAttr("code", CODE);
		render(BASE_PATH + "snStore.html");
	}

    public void byCompany() {
        setAttr("code", CODE);
        render(BASE_PATH + "snStore_byCompany.html");
    }

	public void add() {
		setAttr("code", CODE);
		render(BASE_PATH + "snStore_auto.html");
	}

    //出库
    @ClearShiro
    public void out() {
        setAttr("code", CODE);
        render(BASE_PATH + "snStore_out.html");
    }

	@ClearShiro
	public void addbyhand() {
		setAttr("code", CODE);
		render(BASE_PATH + "snStore_add.html");
	}
	@ClearShiro
	public void inStore(){
        Integer orderId = getParaToInt("orderId");
        if(orderId==null){
            renderJson(error("未查询到相关订单"));
            return;
        }
        Date date = new Date();
        long time = date.getTime();
        Integer t = Integer.parseInt((time+"").substring(0,10));
        List<SnOrderInlog> snOrderInlog = Blade.dao().select("SnStore.findOrderLog", SnOrderInlog.class, Record.create().set("orderId", orderId));
        SnOrderIn snOrderIn = Blade.create(SnOrderIn.class).findById(orderId);
        int error = 0;
        if(snOrderInlog.size()>0){
            for(SnOrderInlog log:snOrderInlog){
                Map map = Blade.dao().selectSingle("SnStore.findKucunByGid", Record.create().set("gid", log.getG_id()), Map.class);
                int kucun = Integer.parseInt(map.get("kucun").toString());//剩余库存
                kucun = kucun + log.getNum();
                BigDecimal allprice = (BigDecimal)map.get("price");//剩余价值
                allprice = allprice.add(log.getTotle_price());
                BigDecimal danjia = new BigDecimal(0.00);
                if(kucun != 0){
                    danjia = allprice.divide(new BigDecimal(kucun),BigDecimal.ROUND_HALF_EVEN);
                }
                BigDecimal price = log.getPrice();
                BigDecimal totle = price.multiply(new BigDecimal(log.getNum()));
                SnStore snStore = new SnStore();
                snStore.setBianhao(t);
                snStore.setIn_time(date);
                snStore.setS_id(snOrderIn.getS_id());
                snStore.setU_id((int)ShiroKit.getUser().getId());
                snStore.setG_id(log.getG_id());
                snStore.setG_price(log.getPrice());
                snStore.setIn_num(log.getNum());
                snStore.setTotle_price(totle);
                snStore.setOrder_id(orderId);
                snStore.setKucun_now(kucun);
                snStore.setPrice_now(allprice);
                snStore.setFinal_price(danjia);
                boolean save = service.save(snStore);
                if(!save){
                    error++;
                }
            }
            int orderId1 = Blade.dao().update("SnStore.updateIsStore", Record.create().set("orderId", orderId));
            if(error==0){
                renderJson(success("入库成功"));
                return;
            }else {
                renderJson(success("部分商品入库失败，请核对"));
                return;
            }
        }else {
            renderJson(error("入库失败"));
        }
	}

	public void edit() {
		String id = getPara(0);
        Map snStore = Blade.dao().selectSingle("SnStore.findById", Record.create().set("id", id), Map.class);
        setAttr("model", JsonKit.toJson(snStore));
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "snStore_edit.html");
	}

	public void view() {
		String id = getPara(0);
		SnStore snStore = service.findById(id);
        Integer in_num = snStore.getIn_num();
        Integer out_num = snStore.getOut_num();
        int type = 0;
        if(in_num != null){
            type = 1;
            setAttr("inType","in");
        }else {
            setAttr("inType","out");
        }
        Map map = Blade.dao().selectSingle("SnStore.findById", Record.create().set("id", id), Map.class);

        Integer bianhao = snStore.getBianhao();
        List<Map> list = Blade.dao().select("SnStore,findByBianhao", Map.class, Record.create().set("bianhao", bianhao));
        setAttr("list",list);
        setAttr("store",map);
        setAttr("model", JsonKit.toJson(snStore));
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "snStore_view.html");
	}

	public void list() {
        String start = getPara("start","");
        String over = getPara("over","");
        String gname = getPara("gname","");
        String company = getPara("company","");
        if(StringKit.isBlank(start)){
            start = "1990-01-01 00:00:00";
        }else {
            start = start + " 00:00:00";
        }
        if(StringKit.isBlank(over)){
            over = "2099-01-01 00:00:00";
        }else {
            over = over + " 23:59:59";
        }
        gname ="%"+ gname + "%";
        company ="%"+ company + "%";
        List<Map> select = Blade.dao().select(LIST_SOURCE, Map.class, Record.create().set("start", start)
                .set("gname",gname).set("company",company).set("over", over));
        Object grid = CommonUtil.fenye(select,getParaToInt("page",1),getParaToInt("rows"),20);
//        Object grid = paginate(LIST_SOURCE);
		renderJson(grid);
	}

	@ClearShiro
    public void listchu() {
        String start = getPara("start","");
        String over = getPara("over","");
        String gname = getPara("gname","");
        String company = getPara("company","");
        if(StringKit.isBlank(start)){
            start = "1990-01-01 00:00:00";
        }else {
            start = start + " 00:00:00";
        }
        if(StringKit.isBlank(over)){
            over = "2099-01-01 00:00:00";
        }else {
            over = over + " 23:59:59";
        }
        gname ="%"+ gname + "%";
        company ="%"+ company + "%";
        List<Map> select = Blade.dao().select("SnStore.listchu", Map.class, Record.create().set("start", start)
                .set("gname",gname).set("company",company).set("over", over));
        Object grid = CommonUtil.fenye(select,getParaToInt("page",1),getParaToInt("rows"),20);
//        Object grid = paginate(LIST_SOURCE);
        renderJson(grid);
    }

	public void save() {
        Date date = new Date();
        long time = date.getTime();
        Integer t = Integer.parseInt((time+"").substring(0,10));
		SnStore snStore = mapping(PERFIX, SnStore.class);
        snStore.setBianhao(t);
        BigDecimal totleprice = snStore.getG_price().multiply(new BigDecimal(snStore.getIn_num()));
        snStore.setTotle_price(totleprice);
        Map map = Blade.dao().selectSingle("SnStore.findKucunByGid", Record.create().set("gid", snStore.getG_id()), Map.class);
        int kucun = Integer.parseInt(map.get("kucun").toString());//剩余库存
        kucun = kucun + snStore.getIn_num();
        BigDecimal allprice = (BigDecimal)map.get("price");//剩余价值
        allprice = allprice.add(totleprice);
        BigDecimal danjia = new BigDecimal(0.00);
        if(kucun != 0){
            danjia = allprice.divide(new BigDecimal(kucun),BigDecimal.ROUND_HALF_EVEN);
        }
        snStore.setKucun_now(kucun);
        snStore.setPrice_now(allprice);
        snStore.setFinal_price(danjia);
        if(snStore!=null){
            snStore.setU_id((int)ShiroKit.getUser().getId());
        }
        if(snStore.getIn_num()!=null){
            snStore.setIn_time(new Date());
        }
        if(snStore.getOut_num()!=null){
            snStore.setOut_time(new Date());
        }
		boolean temp = service.save(snStore);
		if (temp) {
			renderJson(success(SAVE_SUCCESS_MSG));
		} else {
			renderJson(error(SAVE_FAIL_MSG));
		}
	}

    @ClearShiro
    public void outStore() {
        Date date = new Date();
        long time = date.getTime();
        Integer t = Integer.parseInt((time+"").substring(0,10));
        SnStore snStore = mapping(PERFIX, SnStore.class);


        Map map = Blade.dao().selectSingle("SnStore.findKucunByGid", Record.create().set("gid", snStore.getG_id()), Map.class);
        int kucun = Integer.parseInt(map.get("kucun").toString());//剩余库存
        BigDecimal allprice = (BigDecimal)map.get("price");//剩余价值

        BigDecimal danjia = new BigDecimal(0.00);//单价
        if(kucun != 0){
            danjia = allprice.divide(new BigDecimal(kucun),BigDecimal.ROUND_HALF_EVEN);
        }

        BigDecimal totle = danjia.multiply(new BigDecimal(snStore.getOut_num())).multiply(new BigDecimal(-1));//本次出库的价值

        if(kucun < snStore.getOut_num()){
            renderJson(error("库存不足，无法操作"));
            return;
        }
        kucun = kucun - snStore.getOut_num();
        allprice = allprice.add(totle);//总价值

        snStore.setTotle_price(totle);
        snStore.setKucun_now(kucun);
        snStore.setPrice_now(allprice);
        snStore.setFinal_price(danjia);
        snStore.setBianhao(t);






        if(snStore!=null){
            snStore.setU_id((int)ShiroKit.getUser().getId());
        }
        if(snStore.getOut_num()!=null){
            snStore.setOut_time(date);
        }
        boolean temp = service.save(snStore);
        if (temp) {
            renderJson(success(SAVE_SUCCESS_MSG));
        } else {
            renderJson(error(SAVE_FAIL_MSG));
        }
    }

	public void update() {
		SnStore snStore = mapping(PERFIX, SnStore.class);
        if(snStore.getIn_num()!=null && snStore.getOut_num()!=null){
            renderJson(error("一条记录不能同时拥有出入库数量"));
            return;
        }
		boolean temp = service.update(snStore);
		if (temp) {
			renderJson(success(UPDATE_SUCCESS_MSG));
		} else {
			renderJson(error(UPDATE_FAIL_MSG));
		}
	}

	public void remove() {
		String ids = getPara("ids");
		int cnt = service.deleteByIds(ids);
		if (cnt > 0) {
			renderJson(success(DEL_SUCCESS_MSG));
		} else {
			renderJson(error(DEL_FAIL_MSG));
		}
	}
}
